package org.setamv.springcloud.hystrix.comprehesive;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 定义一个Servlet过滤器，用于初始化每一个请求的Hystrix缓存上下文环境
 */
@WebFilter(urlPatterns = "/*", filterName = "hystrix context init filter")
public class HystrixContextInitFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 初始化每一个请求的Hystrix缓存上下文环境
        HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            ctx.shutdown();
        }
    }

    @Override
    public void destroy() {

    }
}
